aboutsummaryrefslogtreecommitdiff
path: root/src/routes/projects/[id]/+page.server.ts
blob: 83d7571d64faef69b58b56a46c89d04e6f3c50d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

import { error, fail, redirect } from '@sveltejs/kit';
import {
	archive as archiveProject,
	getById,
} from '$lib/server/services/projects';
import {
	add,
	loadProjectDashboard,
	loadArchived,
} from '$lib/server/services/routines';
import { completeRoutineAction } from '$lib/server/services/routine-actions';
import { numericId, parseFormString } from '$lib/server/services/validation';
import { Frequency } from '$lib/shared/frequency';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params }) => {
	const id = numericId(params.id);
	const project = await getById(id);
	if (!project || project.archived) {
		throw error(404, 'Projet introuvable');
	}
	const dashboard = await loadProjectDashboard(id, Temporal.Now.instant());
	const archived = await loadArchived(id);
	return {
		project: { id: project.id, name: project.name },
		routines: dashboard.routines,
		healthScore: dashboard.healthScore,
		healthSeries: dashboard.healthSeries,
		archived,
	};
};

export const actions: Actions = {
	addRoutine: async ({ request, params }) => {
		const data = await request.formData();
		const name = parseFormString(data.get('name'));
		if (!name) {
			return fail(400, { error: 'Le nom est requis' });
		}
		try {
			await add(
				numericId(params.id),
				name,
				Frequency.parse(data.get('frequency')?.toString() ?? '').toSpec(),
			);
		} catch {
			return fail(400, { error: 'Fréquence invalide' });
		}
		return { success: true };
	},

	complete: async ({ request }) => {
		const data = await request.formData();
		return completeRoutineAction(data, numericId(data.get('id')));
	},

	archiveProject: async ({ params }) => {
		await archiveProject(numericId(params.id));
		throw redirect(303, '/');
	},
};